package com.yhy.common.security.exception;

import com.yhy.common.core.exception.GlobalServletExceptionHandlerResolver;
import com.yhy.common.core.result.Result;
import com.yhy.common.core.result.ResultEnum;
import com.yhy.common.core.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Jax-li
 */
@Slf4j
@RestControllerAdvice
@ConditionalOnMissingBean(WebFluxAutoConfiguration.class)
public class MyAuthExceptionHandlerResolver extends GlobalServletExceptionHandlerResolver {

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler({OAuth2Exception.class})
    public void invalidGrantException(HttpServletRequest request, HttpServletResponse response, OAuth2Exception ex) {
        Result<String> result = Result.fail(ResultEnum.AUTH_ERROR);
        result.setMessage(ex.getLocalizedMessage());
        error(request, ex, ex.getLocalizedMessage());
        WebUtils.renderJson(response, result);
    }

}
